
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:reabampos/src/reabam/operation/db/models.dart';
import 'package:reabampos/src/reabam/operation/db/objectbox.dart';
import 'package:reabampos/src/reabam/operation/db/objectbox.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/ui/support/support_control_devices.dart';
import 'package:reabampos/src/reabam/ui/support/support_download_db_file.dart';
import 'package:reabampos/src/reabam/ui/support/support_get_good_items.dart';
import 'package:reabampos/src/reabam/ui/support/support_h5_api_cache.dart';
import 'package:reabampos/src/reabam/ui/support/support_handle_photo.dart';
import 'package:reabampos/src/reabam/ui/support/support_offline_cuxiao.dart';
import 'package:reabampos/src/reabam/ui/support/support_offline_order.dart';
import 'package:reabampos/src/reabam/ui/support/support_repay_order.dart';
import 'package:reabampos/src/reabam/ui/support/support_upload_order_paylist.dart';
import 'package:reabampos/src/reabam/ui_self_service/member/pagestate_ss_select_member.dart';
import 'package:reabampos/src/reabam/ui_self_service/shoppingcart/pagestate_ss_manual_input_gooditem_barcode_search.dart';
import 'package:reabampos/src/reabam/ui_self_service/pagestate_ss_login.dart';
import 'package:reabampos/src/reabam/ui_self_service/shoppingcart/pagestate_ss_shoppingcart.dart';
import 'package:reabampos/src/reabam/utils/rb_aliyun_log.dart';
import 'package:reabampos/src/reabam/utils/rb_business.dart';
import 'package:reabampos/src/reabam/utils/rb_color.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_aliyun_log.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:xsdk_flutter_plugin/plugin/x_utils_flutter_plugin.dart';

import 'mine/pagestate_ss_setting_login.dart';

/*
自助收银首页
 */
class StatePageSelfServiceHomeIndex extends XPageState{

  late XFunctionNotifyStateChangeListener _notifyGlobalHandlerListener;

  // late SupportDownloadDBFile supportDownloadDBFile;
  // late SupportRepayOrder supportRepayOrder;
  // late SupportOfflineCuxiao supportOfflineCuxiao;
  // late SupportUploadOrderAndPay supportUploadOrderAndPay;
  // late SupportOfflineOrder supportOfflineOrder;
  // late SupportGetGoodItems supportGetGoodItems;
  // late SupportControlDevices supportControlDevices;
  // late SupportHandlePhoto supportHandlePhoto;

  @override
  void onCreate() {
    super.onCreate();
    RBConfigs.isPageScanType=0;

    //初始化android设备(商米机等)
    _initAndroid();

    //文字转语音
    XTTSUtils.initTts(rate:XFlutterUtils.isiOS()?0.5:1);
    //获取服务端时间
    _checkServerTime();

    //更新设备记录设置
    SupportControlDevices.init(this);


    //登录成功初始化
    _loginSuccessInit();


    // supportDownloadDBFile=SupportDownloadDBFile(this);
    // supportRepayOrder=SupportRepayOrder(this);
    // supportOfflineCuxiao=SupportOfflineCuxiao(this);
    // supportUploadOrderAndPay=SupportUploadOrderAndPay(this);
    // supportOfflineOrder=SupportOfflineOrder(this);
    // supportGetGoodItems=SupportGetGoodItems(this);
    // supportControlDevices=SupportControlDevices(this);
    // supportHandlePhoto=SupportHandlePhoto(this);

    _notifyGlobalHandlerListener=(String key,dynamic value){

      XLogUtils.printLog('---_notifyGlobalHandlerListener,key=$key');
      if(key=='backToLoginPage'){
        //
        startPage(StatePageSelfServiceLogin(),cleanUntilRetainPageName:'/');
      }else if(key=='initAllDevicesNoteSetting'){
        XLogUtils.printLog('---更新设备记录设置');
        SupportControlDevices.initAllDevicesNoteSetting();
      }else if(key=='changeCompany'){
        XLogUtils.printLog('---切换门店');
        //登录成功初始化
        _loginSuccessInit();
      }

      //
      _getWifiIP();

    };

    XNotifyStateChangeUtils.receiveChangeNotify(
      action: RBConfigs.Notify_Global_Handler,
      listener: _notifyGlobalHandlerListener,
    );

  }
  @override
  void onResumed() {
    super.onResumed();
    RBConfigs.isPageScanType=0;

  }

  void _loginSuccessInit(){

    //初始化阿里云日志
    RBBaseApi.initAliyunLog('自助收银');

    String companyId=XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
    XLogUtils.printLog('---开始数据库初始化,companyId=$companyId');
    //objectbox database
    XObjectBoxUtils.create(this,XStringUtils.isEmpty(companyId)?'default_db':companyId);

    //初始化socket设备
    XSocketUtils.init();
    //初始化远程设备(快麦云设备)
    XRemoteDeviceUtils.init();
    //初始化蓝牙设备
    XBluetoothBLEUtils.init();
    //初始化usb设备
    XUsbUtils.init();
    //初始化usbSerial设备
    XUsbSerialUtils.init();

    //重新获取支付方式和商品分类
    RBBaseApi.initGetPayTypeAndGoodType();

    //更新设备记录设置
    SupportControlDevices.initAllDevicesNoteSetting();

    //登录成功重新检测和处理未上传订单2.0
    SupportUploadOrderAndPay.loginInitCheckUnUploadOrderTaskX();

  }


  @override
  void onDestroy() {
    super.onDestroy();
    XNotifyStateChangeUtils.unReceiveChangeNotify(action: RBConfigs.Notify_Global_Handler, listener: _notifyGlobalHandlerListener);
  }

  //初始化android设备(商米机等)
  void _initAndroid() async{

    if(XFlutterUtils.isAndroid()){

      setReceiveNativeMessageCallback_CurrentProject();
      reSetReceiveNativeMessageCallback_XSDKFlutterPlugin();

      //
      Map<String, dynamic> deviceInfo= await XFlutterUtils.getDeviceInfo();
      XLogUtils.printLog('---Android deviceInfo= $deviceInfo');
      dynamic brand =  deviceInfo['brand'];
      dynamic model =  deviceInfo['model'];
      dynamic version =  deviceInfo['version'];

      //初始化支付宝碰一碰设备sdk,参数固定
      Map<String,Object> map_alipayiot={};
      map_alipayiot['appId']='2021004177679101';
      map_alipayiot['pId']='2088611935241475';

      //
      if(XStringUtils.equalsIgnoreCase('SUNMI', brand)){
        //初始化商米机
        XLogUtils.printLog('---初始化商米机');
        RBConfigs.isShangMiDevice=true;
        XFlutterPluginUtils.initShangMiSDK();

        //是否使用商米打印
        RBConfigs.isUserShangMiPrint=XSharePreferencesUtils.getBool(RBConfigs.SP_isUseShangMiPrinter,defaultValue: true);
        RBConfigs.isUserShangMiSerialWeigher=XSharePreferencesUtils.getBool(RBConfigs.SP_isUseShangMiSerialWeigher,defaultValue: true);

        if('$model'.startsWith('T1')||'$model'=='T2'){
          //初始化支付宝碰一碰设备sdk,实测D2_d_2nd android 11 崩溃
          XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
        }else{
          //实测商米D2_xx android 11初始化正常, 开放其他商米设备初始化,如闪退则smile不兼容导致
          XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
        }

      }else if(XStringUtils.equalsIgnoreCase('HUAWEI', brand)){
        //华为平板 初始化支付宝碰一碰设备sdk,实测有些设备闪退,smile不兼容导致
        /*
        cd D:\Android\Sdk\platform-tools
        ./adb devices
        ./adb shell logcat >smile.log
        ./adb -s 192.168.8.98:5555 shell logcat >smile.log
         */

        // if(version=='12'){
        //   //实测华为 android 12 初始化正常
        //   XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
        // }
        //实测华为 android 12 初始化正常, 开放其他华为平板,如闪退则smile不兼容导致
        XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
      }else{
        //开放其他品牌平板,如闪退则smile不兼容导致
        XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
      }

    }
  }

  void reSetReceiveNativeMessageCallback_XSDKFlutterPlugin(){
    if(XFlutterUtils.isAndroid()){
      XFlutterPluginUtils.setReceiveNativeMessageCallback((resultMap) {

        //{"type":"XSecondScreen","data":"{\"type\":\"getOfflineShopCart\"}"}
        String type=resultMap['type']??'';
        if(type=='XSecondScreen'){
          Map<String,dynamic> data=XJsonUtils.json2Map(resultMap['data']);
          String t1=data['type']??'';
          if(t1=='getOfflineShopCart'){
            //第二屏幕需要获得购物车
            //supportGetGoodItems.getOfflineShopCart(isSecondScreen:true);
          }else if(t1=='getH5SaveValue'){
            //
            String key=data['data']??'';
            //_handle_getH5SaveValue(key,isSecondScreen:true);
          }
        }else if(type=='AlipayIot_init'){
          //支付宝碰一碰硬件初始化
          String dataJson=resultMap['data']??'';
          //阿里云日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---AlipayIot初始化返回:$dataJson');

        }else if(type=='AlipayIot_commonPay'){
          //支付宝碰一碰硬件 普通支付
          String dataJson=resultMap['data']??'';
          //runJSFunction(jsFunction_getAppValue('BPaaSCashier',dataJson));

          XLogUtils.printLog('---AlipayIot_commonPay=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---AlipayIot_commonPay返回:$dataJson');

        }else if(type=='AlipayIot_memberPay'){
          //支付宝碰一碰硬件 会员支付
          String dataJson=resultMap['data']??'';
          //runJSFunction(jsFunction_getAppValue('BPaaSNfcMemberPay',dataJson));

          XLogUtils.printLog('---AlipayIot_memberPay=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---AlipayIot_memberPay返回:$dataJson');

        }else if(type=='AlipayIot_memberCard'){
          //支付宝碰一碰硬件 会员开卡登录
          String dataJson=resultMap['data']??'';
          //runJSFunction(jsFunction_getAppValue('BPaaSNfcMember',dataJson));

          XLogUtils.printLog('---AlipayIot_memberCard=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---AlipayIot_memberCard返回:$dataJson');

        }
      });
    }
  }

  MethodChannel methodChannel_project=const MethodChannel('x_project_channel');
  void setReceiveNativeMessageCallback_CurrentProject(){
    if(XFlutterUtils.isAndroid()){

      XFlutterUtils.receiveNativeMessageCallback(methodChannel_project, (resultMap){
        String type=resultMap['type']??'';
        if(type=='android_keyboard_listener'){
          String outputStr=resultMap['data']??'';
          XLogUtils.printLog('---android_keyboard_listener,isPageScanType=${RBConfigs.isPageScanType}, outputStr=$outputStr');

          //test...
          outputStr='40630128';

          if(RBConfigs.isPageScanType==1){
            //扫描搜索商品添加购物车

            Map<String,dynamic> requestMap={};
            requestMap['pageIndex']=1;
            requestMap['pageSize']=20;
            requestMap['sword']=outputStr;

            SupportGetGoodItems.searchGoodItems(
                this,
                requestMap,
                isSearchMainItem:false,
                callback:(Map<String,dynamic> result) {

              List<Map<String, dynamic>> items=result['items']??[];
              int size=items.length;
              XLogUtils.printLog('---搜索数据库结果items,size=$size');

              if(size!=1){
                toast('请重新扫描');
                return;
              }

              //添加到购物车,平铺没有规格
              BeanShoppingCartDBGood item =BeanShoppingCartDBGood.fromJson(items[0]);
              item.specType='0';
              //
              XObjectBoxUtils.saveToShoppingCart(
                  xTag:RBConfigs.Tag_selfService,
                  item:item,
                  isModeAdd:true,
                  onCallback:(res){
                    XNotifyStateChangeUtils.notifyStateChange(
                        action: RBConfigs.NotifyAction_selfService_update_shoppingcart,
                        key: 'key',
                        value: 'value'
                    );
                  }
              );
            }
            );
          }else if(RBConfigs.isPageScanType==2){
            //扫描支付

          }



        }
      });
    }
  }

  void _getWifiIP() async{
    RBConfigs.localIP=await XWifiUtils.getWifiIP();
    XLogUtils.printLog('---localIP=${RBConfigs.localIP}');
  }

  void _checkServerTime(){

    RBBaseApi.getServerTime(
        succeed: (response, Map<String, dynamic> responseMap, Map<String, dynamic> headersResponse) {
          double longt=XNumberUtils.dynamic2double(responseMap['data'])??0.0;
          if(longt>0){
            double dif=(longt-XDateUtils.getCurrentTime_ms()).abs();
            //XLogUtils.printLog('---difTime=$dif');
            if(dif>10*60*1000){
              XFlutterUtils.openAlertDialogDefault(
                  context: context,
                  title: '设备时间',
                  contentStr: '当前设备时间有误,请校准后再使用?',
                  isShowCancelButton: false,
                  onCallbackResult: (String? bt){
                    if('确定'==bt){
                      XFlutterUtils.closeApp();
                    }
                  }
              );
            }

          }
        },
        failed: (String code, String msg) {
          //
        });

  }

  @override
  bool getCanHardwarePressBack() {
    return false;
  }

  @override
  Widget getBodyWidget(BuildContext context) {
    return XWidgetUtils.getLayoutContainer(
        child:XWidgetUtils.getLayoutColumn(
            children: [
              XWidgetUtils.getLayoutContainer(
                  margin: XWidgetUtils.getEdgeInsets(50, 46, 0, 0),
                  child: XWidgetUtils.getLayoutRow(
                      children: [
                        XImageUtils.getImageWidgetWithAsset(
                          'reabam_logo_3.png',
                          width: 200,
                          height: 52,
                        ),
                        const Spacer(),
                        XWidgetUtils.getWidgetGestureDetector(
                            child: XWidgetUtils.getLayoutContainer(
                                backgroundColor: Colors.white,
                                child: XWidgetUtils.getLayoutRow(
                                    children: [
                                      XImageUtils.getImageWidgetWithAsset(
                                        'setting1.png',
                                        width: 46,
                                        height: 46,
                                      ),
                                      XWidgetUtils.getWidgetText(
                                          '设置',
                                          style: XStyleUtils.getTextStyle(
                                            fontSize: 38,
                                            color: RBColors.reabamColor4,
                                          ),
                                          padding: XWidgetUtils.getEdgeInsets(7, 0, 50, 0)
                                      )
                                    ]
                                )
                            ),
                            onTap: (){
                              startPage(PageStateSelfServiceSettingLogin());
                            }
                        )
                      ]
                  )
              ),
              XWidgetUtils.getLayoutContainer(
                  margin: XWidgetUtils.getEdgeInsets(0, 183, 0, 0),
                  alignment: Alignment.center,
                  child: XWidgetUtils.getWidgetText(
                    '欢迎使用自助收银',
                    textAlign:TextAlign.center,
                    style: XStyleUtils.getTextStyle(
                      fontSize: 80,
                      color: RBColors.reabamColor4,
                    ),
                  )
              ),
              XWidgetUtils.getLayoutContainer(
                  margin: XWidgetUtils.getEdgeInsets(125, 91, 125, 0),
                  child: XWidgetUtils.getLayoutRow(
                      crossAxisAlignment:CrossAxisAlignment.start,
                      children: [
                        XWidgetUtils.getLayoutContainer(
                            child: XWidgetUtils.getLayoutColumn(
                                crossAxisAlignment :CrossAxisAlignment.center,
                                shrinkWrap:true,
                                children: [
                                  XImageUtils.getImageWidgetWithAsset(
                                    'ss_homeindex_1.png',
                                    width: 120,
                                    height: 120,
                                  ),
                                  XWidgetUtils.getWidgetText(
                                    '选择会员\n或非会员购物',
                                    textAlign:TextAlign.center,
                                    style: XStyleUtils.getTextStyle(
                                      fontSize: 26,
                                      color: RBColors.reabamColor4,
                                    ),
                                  ),
                                ]
                            )
                        ),

                        XWidgetUtils.getLayoutExpanded(
                            XWidgetUtils.getLayoutContainer(
                              alignment: Alignment.topCenter,
                              margin: XWidgetUtils.getEdgeInsets(0, 45, 0, 0),
                              child: XImageUtils.getImageWidgetWithAsset(
                                'ss_arr_right.png',
                                width: 40,
                                height: 40,
                              ),
                            )
                        ),
                        XWidgetUtils.getLayoutExpanded(
                          XWidgetUtils.getLayoutContainer(
                              child: XWidgetUtils.getLayoutColumn(
                                  crossAxisAlignment :CrossAxisAlignment.center,
                                  shrinkWrap:true,
                                  children: [
                                    XImageUtils.getImageWidgetWithAsset(
                                      'ss_homeindex_2.png',
                                      width: 120,
                                      height: 120,
                                    ),
                                    XWidgetUtils.getWidgetText(
                                      '扫一扫\n商品条形码',
                                      textAlign:TextAlign.center,
                                      style: XStyleUtils.getTextStyle(
                                        fontSize: 26,
                                        color: RBColors.reabamColor4,
                                      ),
                                    ),
                                  ]
                              )
                          ),
                        ),
                        XWidgetUtils.getLayoutExpanded(
                            XWidgetUtils.getLayoutContainer(
                              alignment: Alignment.topCenter,
                              margin: XWidgetUtils.getEdgeInsets(0, 45, 0, 0),
                              child: XImageUtils.getImageWidgetWithAsset(
                                'ss_arr_right.png',
                                width: 40,
                                height: 40,
                              ),
                            )
                        ),
                        XWidgetUtils.getLayoutContainer(
                            child: XWidgetUtils.getLayoutColumn(
                                crossAxisAlignment :CrossAxisAlignment.center,
                                shrinkWrap:true,
                                children: [
                                  XImageUtils.getImageWidgetWithAsset(
                                    'ss_homeindex_3.png',
                                    width: 120,
                                    height: 120,
                                  ),
                                  XWidgetUtils.getWidgetText(
                                    '完成支付\n（等待打印小票）',
                                    textAlign:TextAlign.center,
                                    style: XStyleUtils.getTextStyle(
                                      fontSize: 26,
                                      color: RBColors.reabamColor4,
                                    ),
                                  ),
                                ]
                            )
                        ),
                      ]
                  )
              ),
              XWidgetUtils.getLayoutContainer(
                  margin: XWidgetUtils.getEdgeInsets(0, 166, 0, 0),
                  alignment: Alignment.center,
                  child: XImageUtils.getImageWidgetWithAsset(
                    'ss_homeindex_big_logo.png',
                    width: 531,
                    height: 531,
                  )
              ),
              XWidgetUtils.getWidgetGestureDetector(
                  child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
                      margin: XWidgetUtils.getEdgeInsets(91, 137, 91, 0),
                      radius_bottomLeft: 16,
                      radius_bottomRight: 16,
                      radius_topRight: 16,
                      radius_topLeft: 16,
                      height: 120,
                      alignment: Alignment.center,
                      backgroundColor: RBColors.reabamColor4,
                      child:XWidgetUtils.getWidgetText(
                        '会员结算',
                        textAlign:TextAlign.center,
                        style: XStyleUtils.getTextStyle(
                          fontSize: 46,
                          color: Colors.white,
                        ),
                      )
                  ),
                  onTap: (){
                    startPage(PageStateSelfServiceSelectMember());
                  }
              ),
              XWidgetUtils.getWidgetGestureDetector(
                  child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
                      margin: XWidgetUtils.getEdgeInsets(91, 42, 91, 0),
                      radius_bottomLeft: 16,
                      radius_bottomRight: 16,
                      radius_topRight: 16,
                      radius_topLeft: 16,
                      height: 120,
                      alignment: Alignment.center,
                      backgroundColor: Colors.white,
                      borderColor: RBColors.reabamColor4,
                      borderWidth: 3,
                      child:XWidgetUtils.getWidgetText(
                        '非会员结算',
                        textAlign:TextAlign.center,
                        style: XStyleUtils.getTextStyle(
                          fontSize: 46,
                          color: RBColors.reabamColor4,
                        ),
                      )
                  ),
                  onTap: (){
                    startPage(PageStateSelfServiceShoppingcart(member:null));
                  }
              )
            ]
        )
    );
  }

  @override
  void onStart() {
    _initSomeData();
  }

  @override
  Future<void> updateData({int pageIndex = 1}) async {
  }


  _initSomeData(){
    RBBaseApi.getShopCartDetail(
        succeed: (response, Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {
          dynamic data=responseMap['data'];

          /*
            导购
            {
			"rate":null,
			"staffCode":"",
			"staffId":"3c38f8543a714fab84ff6d6521afeacc",
			"staffName":"杨定雯"
		}
             */
          dynamic staff=data?['staff'];
          XSharePreferencesUtils.saveString(RBConfigs.SP_staff, XJsonUtils.obj2Json(staff));

        },
        failed: (String code, String msg) {
          //
        });

  }


  @override
  Color getXPageBackgroundColor() {
    return Colors.white;
  }


}